// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init({ env: process.env.Env });
const Towxml = require('towxml');
const db = cloud.database();
const _ = db.command;
const towxml = new Towxml();

cloud.init();

// 云函数入口函数
exports.main = async (event) => {
    switch (event.action) {
        case 'getPostsDetail': {
            return getPostsDetail(event)
        }
        case 'addPostComment': {
            return addPostComment(event)
        }
        case 'addPostChildComment': {
            return addPostChildComment(event)
        }
        case 'addPostCollection': {
            return addPostCollection(event)
        }
        case 'deletePostCollectionOrZan': {
            return deletePostCollectionOrZan(event)
        }
        case 'addPostZan': {
            return addPostZan(event)
        }
        case 'addPostQrCode': {
            return addPostQrCode(event)
        }
        default:
            break
    }
}

/**
 * 新增文章二维码
 * @param {} event
 */
async function addPostQrCode(event) {
    //let scene = 'timestamp=' + event.timestamp;
    let result = await cloud.openapi.wxacode.getUnlimited({
        scene: event.postId,
        page: 'pages/detail/detail'
    });

    if (result.errCode === 0) {
        let upload = await cloud.uploadFile({
            cloudPath: event.postId + '.png',
            fileContent: result.buffer,
        });

        await db.collection("smallTechnology_posts").doc(event.postId).update({
            data: {
                qrCode: upload.fileID
            }
        });

        let fileList = [upload.fileID];
        let resultUrl = await cloud.getTempFileURL({
            fileList,
        })
        return resultUrl.fileList
    }

    return []

}

/**
 * add a comment
 * @param {} event
 */
async function addPostComment(event) {

    let task = db.collection('smallTechnology_posts').doc(event.commentContent.postId).update({
        data: {
            totalComments: _.inc(1)
        }
    });
    await db.collection("smallTechnology_comments").add({
        data: event.commentContent
    });
    let result = await task;
    console.info(result)
}

/**
 * add a sub comment
 * @param {} event
 */
async function addPostChildComment(event) {

    let task = db.collection('smallTechnology_posts').doc(event.postId).update({
        data: {
            totalComments: _.inc(1)
        }
    });

    await db.collection('smallTechnology_comments').doc(event.id).update({
        data: {
            childComment: _.push(event.comments)
        }
    })
    await task;
}

/**
 * processing article collection
 * @param {*} event
 */
async function addPostCollection(event) {
    console.info("处理addPostCollection方法开始")
    console.info(event);
    let postRelated = await db.collection('smallTechnology_posts_related').where({
        openId: event.openId === undefined ? event.userInfo.openId : event.openId,
        postId: event.postId,
        type: event.type
    }).get();

    let task = db.collection('smallTechnology_posts').doc(event.postId).update({
        data: {
            totalCollection: _.inc(1)
        }
    });

    if (postRelated.data.length === 0) {
        let result = await db.collection('smallTechnology_posts_related').add({
            data: {
                openId: event.openId === undefined ? event.userInfo.openId : event.openId,
                postId: event.postId,
                postTitle: event.postTitle,
                postUrl: event.postUrl,
                postDigest: event.postDigest,
                type: event.type,
                createTime: new Date().toFormat("YYYY-MM-DD")
            }
        });
        console.info(result)
    }

    let result = await task;
    console.info(result)
}

/**
 * processing praise
 * @param {} event
 */
async function addPostZan(event) {

    let postRelated = await db.collection('smallTechnology_posts_related').where({
        openId: event.openId === undefined ? event.userInfo.openId : event.openId,
        postId: event.postId,
        type: event.type
    }).get();

    let task = db.collection('smallTechnology_posts').doc(event.postId).update({
        data: {
            totalZans: _.inc(1)
        }
    });

    if (postRelated.data.length === 0) {
        await db.collection('smallTechnology_posts_related').add({
            data: {
                openId: event.openId === undefined ? event.userInfo.openId : event.openId,
                postId: event.postId,
                postTitle: event.postTitle,
                postUrl: event.postUrl,
                postDigest: event.postDigest,
                type: event.type,
                createTime: new Date().toFormat("YYYY-MM-DD")
            }
        });
    }
    let result = await task;
    console.info(result)
}

/**
 * remove collection like
 * @param {} event
 */
async function deletePostCollectionOrZan(event) {
    let result = await db.collection('smallTechnology_posts_related').where({
        openId: event.openId === undefined ? event.userInfo.openId : event.openId,
        postId: event.postId,
        type: event.type
    }).remove();
    console.info(result)
}

/**
 * get article details
 * @param event
 */
async function getPostsDetail(event) {
    console.info("启动getPostsDetail");
    console.info(event);
    let post = await db.collection("smallTechnology_posts").doc(event.id).get();
    if (post.code) {
        return "";
    }
    if (!post.data) {
        return "";
    }
    let data = post.data;
    // direct page views when getting articles add one
    let task = db.collection('smallTechnology_posts').doc(event.id).update({
        data: {
            totalVisits: _.inc(1)
        }
    });
    data.content = await convertPosts(data.content, "html");
    data.totalVisits = data.totalVisits + 1;
    await task;
    return data
}

/**
 * convert the program article
 * @param content
 * @param type
 */
async function convertPosts(content, type) {
    let res;
    if (type === 'markdown') {
        res = await towxml.toJson(content || '', 'markdown');
    } else {
        res = await towxml.toJson(content || '', 'html');
    }
    return res;

}